package com.dingwen.serializable.controller;

import com.alibaba.fastjson.JSON;
import com.dingwen.serializable.common.dto.RequestDto;
import com.dingwen.serializable.proto.Request;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.util.JsonFormat;
import com.google.protobuf.util.Timestamps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.UUID;

/**
 * 测试控制器
 *
 * @author dingwne
 * @date 2021/12/14
 */
@Slf4j
@RestController
@RequestMapping("/test")
public class TestController {
    @PostMapping(value = "/protobuf")
    public String testProto(HttpServletRequest request) throws InvalidProtocolBufferException {
        Request.Builder builder = Request.newBuilder()
                .setId(UUID.randomUUID().toString())
                .setClientIp("192.168.1.1")
                .setAccept("*")
                .setChannel("network")
                .setMapping("/test/")
                .setFerryType("ifa")
                .setSendTime(Timestamps.fromMillis(System.currentTimeMillis()))
                .setClientName("test");
        Request msg = builder.build();
        String fileName = "E:\\fgap\\file\\pb\\" + msg.getId() + ".pb";
        write(msg, fileName);
        Request read = read(fileName);
        System.out.println(read);
        return read.toString();
    }

    public void write(Request msg, String fileName) {
        log.info("[报文名称]{}", fileName);
        try {
            File file = new File(fileName);
            FileOutputStream out = new FileOutputStream(file);
            msg.writeDelimitedTo(out);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public Request read(String fileName) {
        Request msg = null;
        try {
            FileInputStream input = new FileInputStream(fileName);
            do {
                msg = Request.parseDelimitedFrom(input);
            } while (msg == null);
            input.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return msg;
    }


    @PostMapping("/json")
    public Request testJson() {
        Request.Builder builder = Request.newBuilder()
                .setId(UUID.randomUUID().toString())
                .setClientIp("192.168.1.2")
                .setAccept("*")
                .setChannel("network")
                .setMapping("/test")
                .setFerryType("ifa")
                .setSendTime(Timestamps.fromMillis(System.currentTimeMillis()))
                .setClientName("test");
        Request msg = builder.build();
        String fileName = "E:\\fgap\\file\\json\\" + msg.getId() + ".json";
        writeJSON(msg, fileName);
        Request request = readJSON(fileName);
        return readJSON(fileName);
    }

    public void writeJSON(Request msg, String fileName) {
        String data = null;
        try {
            data = JsonFormat.printer().includingDefaultValueFields().print(msg);
        } catch (InvalidProtocolBufferException e) {
            e.printStackTrace();
        }
        writer(fileName, data);
    }

    public void writer(String fileName, String data) {
        try {
            log.info("[报文名称]{}", fileName);
            File file = new File(fileName);
            FileUtils.writeStringToFile(file, data, "UTF-8", false);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public Request readJSON(String fileName) {
        File file = new File(fileName);
        String requestJson = readJSON(file);
        Request.Builder builder = Request.newBuilder();
        if (StringUtils.hasText(requestJson)) {
            try {
                JsonFormat.parser().merge(requestJson, builder);
                return builder.build();
            } catch (InvalidProtocolBufferException e) {
                e.printStackTrace();
            }
        } else {
            return null;
        }
        return null;
    }

    public String readJSON(File file) {
        String jsonStr = "";
        try {
            jsonStr = FileUtils.readFileToString(file, "UTF-8");
            return jsonStr;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }


    @PostMapping("/fastjson")
    public Object testFastjson() {
        RequestDto dto = new RequestDto();
        dto.setId(UUID.randomUUID().toString());
        dto.setClientIp("172.88.0.11");
        dto.setAccept("*");
        dto.setChannel("network");
        dto.setMapping("/test");
        dto.setFerryType("ifa");
        dto.setSendTime(new Timestamp(System.currentTimeMillis()));
        dto.setClientName("test");

        String fileName = "E:\\fgap\\file\\fastjson\\" + dto.getId() + ".json";
        writeJSON(dto, fileName);

        return readFastJSON(fileName);
    }

    public void writeJSON(RequestDto msg, String fileName) {
        String data = JSON.toJSONString(msg);
        writer(fileName, data);
    }

    public RequestDto readFastJSON(String fileName) {
        File file = new File(fileName);
        String requestJson = readJSON(file);
        Request.Builder builder = Request.newBuilder();
        if (StringUtils.hasText(requestJson)) {
            return JSON.parseObject(requestJson, RequestDto.class);
        } else {
            return null;
        }
    }

}

